import { login, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const useLoginUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      username: '',
      nickName: '',
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const verifyCode = userInfo.verifyCode
        const verifyKey = userInfo.verifyKey
        return new Promise((resolve, reject) => {
          login(username, password, verifyCode, verifyKey).then(res => {
            setToken(res)
            this.token = res
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getLoginUserInfo() {
        return new Promise((resolve, reject) => {
          getUserInfo().then(user => {
            this.id = user.id
            this.username = user.username
            this.nickName = user.nickName
            this.permissions = user.permissions
            resolve(user)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.permissions = []
            removeToken()
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })

export default useLoginUserStore
